import java.util.Arrays;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @Author Stringzhua
 * @Date 2024/11/4 10:12
 * description:
 */
public class Demo03 {
    private int[] counts = new int[10];
    //运行并发读取,写入操作时,不允许读取
    private final ReadWriteLock lock = new ReentrantReadWriteLock();
    private Lock readLock = lock.readLock();//读锁
    private Lock writeLock = lock.writeLock();//写锁

    public void inc(int index) {
        //获取写锁,发生写入操作时,不允许 其它线程写入或读取(悲观锁)
        final Lock lock = this.readLock;
        lock.lock();
        try {
            counts[index] += 1;
        } finally {
            lock.unlock();
        }
    }

    public int[] get() {
        //获取读锁,允许并发读取,当发生写入操作时,不允许读取
        final Lock lock = this.readLock;
        lock.lock();
        try {
            return Arrays.copyOf(counts, counts.length);
        } finally {
            lock.unlock();
        }
    }
}
